//
//  DFUStatusUpgradeVC.swift
//  SDKDebuggingDemo
//
//  Created by Qinsz on 2019/10/29.
//  Copyright © 2019年 QinszQSZ. All rights reserved.
//

import UIKit
import iOSDFULibrary

class DFUStatusUpgradeVC: UIViewController,LoggerDelegate,DFUServiceDelegate,DFUProgressDelegate {

    
    @IBOutlet weak var adaptNumField: UITextField!
    
    private let shell = KCTSingleBLEShell.sharedInstance
    
    private var progress:Int = -1

    @IBOutlet weak var textView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

    }


    @IBAction func clickBack(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func clickReadAdaptNumFromCache(_ sender: Any) {
        
        adaptNumField.text = nil
        
        if shell.isConnected == false {
            SVProgressHUD.showInfo(withStatus: "蓝牙未连接")
            return
        }
        
        guard let mac = shell.currentPeripheral?.macString else{
            SVProgressHUD.showInfo(withStatus: "当前连接的设备缺少Mac地址信息")
            self._clearTempInfos()
            return
        }
        
        // 查询缓存的适配号
        let num = UserDefaults.standard.integer(forKey: mac)
        if num <= 0 {
            SVProgressHUD.showInfo(withStatus: "没有找到缓存的适配号")
            self._clearTempInfos()
        }else {
            adaptNumField.text = "\(num)"
        }
        
    }
    
    @IBAction func clickStart(_ sender: Any) {
        
        self.view.endEditing(true)
        
        if shell.isConnected == false{
            SVProgressHUD.showInfo(withStatus: "蓝牙未连接")
            self._clearTempInfos()
            return
        }
        
        guard let mac = shell.currentPeripheral?.macString else{
            SVProgressHUD.showInfo(withStatus: "当前连接的设备缺少Mac地址信息")
            self._clearTempInfos()
            return
        }
        
        if let name = shell.currentPeripheral?.name?.lowercased(),name.contains("dfutarg") {
            
            if let str = adaptNumField.text, let num = Int(str) {
                let ok = UIAlertAction.init(title: "继续", style: .default) {[weak self] (action) in
                    self?.requestFirmwareVersionInfos(num: num, mac: mac)
                }
                let cancel = UIAlertAction.init(title: "取消", style: .cancel) { (action) in
                    
                }
                let alertController = UIAlertController.init(title: "即将进行DFU升级", message: "Mac地址:\(mac)\n适配号:\(num)", preferredStyle: .alert)
                alertController.addAction(ok)
                alertController.addAction(cancel)
                self.present(alertController, animated: true, completion: nil)
                
            }else{
                SVProgressHUD.showInfo(withStatus: "适配号输入有误")
            }
            
            
            
        }else{
            SVProgressHUD.showInfo(withStatus: "设备没有处于DFU模式")
            self._clearTempInfos()
        }
        
    }
    
    
    
    func requestFirmwareVersionInfos(num:Int,mac:String) {
        
        SVProgressHUD.show(withStatus: "获取固件版本...")
        
        let versionTask = KCTHTTPSession.share.FirmwareInfoTask(fromProduct: false,appKey: TestAPPKey, secretKey: TestSecretKey, adaptiveNum: num) {[weak self] (infos, error) in
            
            DispatchQueue.main.async {
                
                if let err = error {
                    IPrint("\(err)\n")
                    self?.textView.text = err.description
                    SVProgressHUD.showError(withStatus: err.description)
                    self?._clearTempInfos()
                    return
                }
                
                
                guard let `infos` = infos else{
                    // 没有固件信息
                    IPrint("线上没有固件信息（适配号=\(num)）")
                    SVProgressHUD.dismiss()
                    self?.textView.text = "线上没有固件信息（适配号=\(num)）"
                    self?._clearTempInfos()
                    return
                }
                
                //请求资源包
                self?.requestFirmwareFile(fileUrl: infos.file,mac: mac)
            }
        }
        versionTask?.resume()
    }
    
    
    //MARK: - Step_03 获取固件升级资源文件
    func requestFirmwareFile(fileUrl:String,mac:String){
        
        DispatchQueue.main.async {
            
            SVProgressHUD.show(withStatus: "获取固件升级文件...")
            let `fileUrl` = fileUrl.replacingOccurrences(of: " ", with: "%20")
            if let url = URL.init(string: fileUrl){
                let request = URLRequest.init(url: url)
                let session = URLSession.shared
                let task = session.dataTask(with: request) {[weak self] (data, rsp, error) in
                    DispatchQueue.main.async {
                        
                        if let `data` = data{
                            //判断Mac是否匹配
                            if let s = self,s.shell.isConnected,let m = s.shell.currentPeripheral?.macString,m == mac {
                                s.startDFU(fileData: data, peripheral: s.shell.currentPeripheral!)
                            }else{
                                SVProgressHUD.showInfo(withStatus: "Mac地址匹配异常，停止升级")
                                self?._clearTempInfos()
                            }
                        }else{
                            let errInfos = "获取固件升级文件失败"
                            SVProgressHUD.showError(withStatus: errInfos)
                            IPrint("\(errInfos)\n")
                            self?.textView.text = errInfos
                            self?._clearTempInfos()
                        }
                    }
                }
                task.resume()
            }else{
                let errInfos = "初始化固件地址URL错误:urlstr = \(fileUrl)"
                SVProgressHUD.showError(withStatus: errInfos)
                IPrint("\(errInfos)\n")
                self.textView.text = errInfos
                self._clearTempInfos()
            }
            
        }
        
    }
    
    
    
    func startDFU(fileData:Data,peripheral:CBPeripheral) {
        
        let selectedFirmware = DFUFirmware.init(zipFile: fileData)
        
        if let firmware = selectedFirmware {
            let queue = DispatchQueue.global()
            let main = DispatchQueue.main
            var initialtor = DFUServiceInitiator.init(queue: queue, delegateQueue: main, progressQueue: main, loggerQueue: main)
            initialtor = initialtor.with(firmware: firmware)
            initialtor.logger = self
            initialtor.delegate = self
            initialtor.progressDelegate = self
            
            let _ = initialtor.start(target: peripheral)
        }else{
            let message = "创建DFUFirmware失败"
            SVProgressHUD.showError(withStatus: message)
            self.textView.text = message
            self._clearTempInfos()
        }
        
    }
    
    
    
    func dfuProgressDidChange(for part: Int, outOf totalParts: Int, to progress: Int, currentSpeedBytesPerSecond: Double, avgSpeedBytesPerSecond: Double) {
        
        self.progress = progress
        IPrint("升级进度:\npatr=\(part)\ntotalPart=\(totalParts)\nprogress=\(progress)%\ncurrentSpeed=\(currentSpeedBytesPerSecond)bit/s\navSpeed=\(avgSpeedBytesPerSecond)bit/s\n")
        self.textView.text = "升级进度:\npatr=\(part)\ntotalPart=\(totalParts)\nprogress=\(progress)%\ncurrentSpeed=\(currentSpeedBytesPerSecond)bit/s\navSpeed=\(avgSpeedBytesPerSecond)bit/s\n"
        SVProgressHUD.show(withStatus: "\(progress)%")
        
    }
    
    func dfuStateDidChange(to state: DFUState) {
        if state == .disconnecting {
            
            if progress >= 100 {
                IPrint("固件升级成功!!!\n")
                SVProgressHUD.showSuccess(withStatus: "升级成功")
                self.textView.text = "升级成功"
                self._clearTempInfos()
            }else{
                IPrint("固件升级失败:dfu状态改变为\(state)")
                SVProgressHUD.showSuccess(withStatus: "固件升级失败:dfu状态改变为\(state)")
                self.textView.text = "固件升级失败:dfu状态改变为\(state)"
                self._clearTempInfos()
            }
        }
    }
    
    func dfuError(_ error: DFUError, didOccurWithMessage message: String) {
        IPrint("固件升级失败:error=\(error),\(message)\n")
        SVProgressHUD.showError(withStatus: "升级失败")
        self._clearTempInfos()
    }
    
    func logWith(_ level: LogLevel, message: String) {
        IPrint("DFULog:leval=\(level),message=\(message)\n")
    }
    
    
    
    func _clearTempInfos() {
        self.progress = -1
    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

}
